package com.mms.interceptor;

import com.mms.pojo.UserInfo;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",
        value = {"/administrators/*",
                "/medical/*",
                "/primary/*",
                "/reserve/*"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    /**
     * 拦截 未登录
     *
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //获取 session
        HttpSession session = ((HttpServletRequest) request).getSession();
        //获取对象 userinfo
        UserInfo userinfo = (UserInfo) session.getAttribute("userinfo");
        //判断用户是否 登录了
        if (userinfo == null) {
            //没登录 就 重定向到 errorJsp
            String contextPath = session.getServletContext().getContextPath();
            ((HttpServletResponse) response).sendRedirect(contextPath + "/errorJsp");
            return;
        }
        //登录了 放行
        chain.doFilter(request, response);
    }
}
